package com.jeesite.modules.web;

import com.jeesite.common.web.BaseController;
import com.jeesite.modules.entity.PaymentOrder;
import com.jeesite.modules.service.DonationService;
import com.jeesite.modules.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMethod;

import jakarta.servlet.http.HttpServletRequest;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Enumeration;
import java.io.BufferedReader;

/**
 * 支付控制器 - 真实SDK实现
 * @author LaVenderGong
 * @version 2025-08-16
 */
@RestController
@RequestMapping("/payment")
public class PaymentController extends BaseController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private DonationService donationService;

    /**
     * CORS测试接口
     * @return 简单的测试响应
     */
    @GetMapping("/test")
    public Map<String, Object> testCors() {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "CORS配置正常");
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }

    /**
     * 测试支付宝配置
     * @return 配置检查结果
     */
    @GetMapping("/alipay/test-config")
    public Map<String, Object> testAlipayConfig() {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean configValid = paymentService.checkAlipayConfig();
            result.put("success", true);
            result.put("configValid", configValid);
            result.put("message", configValid ? "支付宝配置正常" : "支付宝配置不完整");
            return result;
        } catch (Exception e) {
            logger.error("检查支付宝配置失败", e);
            result.put("success", false);
            result.put("message", "检查配置失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 初始化数据库表
     * @return 初始化结果
     */
    @PostMapping("/init-database")
    public Map<String, Object> initDatabase() {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = paymentService.initDatabase();
            result.put("success", success);
            result.put("message", success ? "数据库初始化成功" : "数据库初始化失败");
            return result;
        } catch (Exception e) {
            logger.error("数据库初始化失败", e);
            result.put("success", false);
            result.put("message", "数据库初始化失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 创建支付宝预创建订单（扫码支付）
     * @param request 支付请求，包含订单ID
     * @return 支付结果，包含二维码链接
     */
    @PostMapping("/alipay/precreate")
    public Map<String, Object> createAlipayPrecreateOrder(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();

        try {
            String orderId = (String) request.get("orderId");
            if (orderId == null || orderId.isEmpty()) {
                result.put("success", false);
                result.put("message", "订单ID不能为空");
                return result;
            }

            String amountStr = request.getOrDefault("amount", "10.00").toString();
            String subject = (String) request.getOrDefault("subject", "KBB服务器捐赠");
            String body = (String) request.getOrDefault("body", "感谢您对KBB服务器的支持！");
            String donorName = (String) request.getOrDefault("donorName", "匿名用户");

            logger.info("支付宝预创建请求: orderId={}, amount={}, subject={}, donorName={}",
                       orderId, amountStr, subject, donorName);

            // 先创建数据库记录
            boolean dbResult = donationService.createDonationAndPaymentOrder(
                orderId,
                new BigDecimal(amountStr),
                donorName,
                subject,
                "ALIPAY"
            );

            if (!dbResult) {
                result.put("success", false);
                result.put("message", "创建订单记录失败");
                return result;
            }

            // 然后调用支付宝预创建API
            Map<String, Object> payResult = paymentService.createAlipayPrecreateOrderDirect(
                orderId, new BigDecimal(amountStr), subject, body);

            logger.info("支付宝预创建结果: {}", payResult.get("success"));
            return payResult;

        } catch (Exception e) {
            logger.error("创建支付宝预创建订单失败", e);
            result.put("success", false);
            result.put("message", "创建支付预创建订单失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 创建支付宝支付订单
     * @param request 支付请求，包含订单ID
     * @return 支付结果，包含支付页面HTML
     */
    @PostMapping("/alipay")
    public Map<String, Object> createAlipayOrder(@RequestBody PaymentRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取支付订单
            PaymentOrder order = paymentService.getPaymentOrder(request.getOrderId());
            if (order == null) {
                result.put("success", false);
                result.put("message", "订单不存在");
                return result;
            }
            
            // 创建支付宝支付订单
            Map<String, Object> payResult = paymentService.createAlipayOrder(order);
            return payResult;
            
        } catch (Exception e) {
            logger.error("创建支付宝订单失败", e);
            result.put("success", false);
            result.put("message", "创建支付订单失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 创建微信支付订单
     * @param request 支付请求，包含订单ID
     * @return 支付结果，包含二维码链接
     */
    @PostMapping("/wechat")
    public Map<String, Object> createWechatOrder(@RequestBody PaymentRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取支付订单
            PaymentOrder order = paymentService.getPaymentOrder(request.getOrderId());
            if (order == null) {
                result.put("success", false);
                result.put("message", "订单不存在");
                return result;
            }
            
            // 创建微信支付订单
            Map<String, Object> payResult = paymentService.createWechatOrder(order);
            return payResult;
            
        } catch (Exception e) {
            logger.error("创建微信支付订单失败", e);
            result.put("success", false);
            result.put("message", "创建支付订单失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 创建云闪付支付订单
     * @param request 支付请求，包含订单ID
     * @return 支付结果，包含支付链接或二维码
     */
    @PostMapping("/unionpay")
    public Map<String, Object> createUnionpayOrder(@RequestBody PaymentRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取支付订单
            PaymentOrder order = paymentService.getPaymentOrder(request.getOrderId());
            if (order == null) {
                result.put("success", false);
                result.put("message", "订单不存在");
                return result;
            }

            // 创建云闪付支付订单
            Map<String, Object> payResult = paymentService.createUnionpayOrder(order);
            return payResult;

        } catch (Exception e) {
            logger.error("创建云闪付订单失败", e);
            result.put("success", false);
            result.put("message", "创建支付订单失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 测试支付宝回调接口是否可访问
     */
    @GetMapping("/callback/alipay/test")
    public Map<String, Object> testAlipayCallback() {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "支付宝回调接口可以正常访问");
        result.put("timestamp", new Date());
        logger.info("支付宝回调测试接口被调用");
        return result;
    }

    /**
     * 模拟支付宝回调测试 (GET版本，方便浏览器测试)
     */
    @GetMapping("/callback/alipay/mock/{orderId}")
    public Map<String, Object> mockAlipayCallbackGet(@PathVariable String orderId) {
        return mockAlipayCallback(orderId);
    }

    /**
     * 模拟支付宝回调测试
     */
    @PostMapping("/callback/alipay/mock/{orderId}")
    public Map<String, Object> mockAlipayCallback(@PathVariable String orderId) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("模拟支付宝回调，订单号: {}", orderId);

            // 模拟支付宝回调参数
            Map<String, String> params = new HashMap<>();
            params.put("out_trade_no", orderId);
            params.put("trade_status", "TRADE_SUCCESS");
            params.put("total_amount", "10.00");
            params.put("trade_no", "2025081922001234567890");

            // 调用支付成功处理
            boolean success = donationService.handlePaymentSuccess(orderId, "2025081922001234567890", "mock_callback_data");

            if (success) {
                result.put("success", true);
                result.put("message", "模拟回调处理成功");
                logger.info("模拟支付宝回调处理成功，订单号: {}", orderId);
            } else {
                result.put("success", false);
                result.put("message", "模拟回调处理失败");
                logger.error("模拟支付宝回调处理失败，订单号: {}", orderId);
            }

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "模拟回调处理异常: " + e.getMessage());
            logger.error("模拟支付宝回调处理异常，订单号: " + orderId, e);
        }

        return result;
    }

    /**
     * 支付宝回调处理
     * 支付宝会通过POST方式发送回调通知
     * @param request HTTP请求对象，包含支付宝回调参数
     * @return 处理结果，success表示处理成功，failure表示处理失败
     */
    @PostMapping("/callback/alipay")
    public String handleAlipayCallback(HttpServletRequest request) {
        try {
            // 获取支付宝回调参数
            Map<String, String> params = new HashMap<>();
            Enumeration<String> parameterNames = request.getParameterNames();
            while (parameterNames.hasMoreElements()) {
                String paramName = parameterNames.nextElement();
                String paramValue = request.getParameter(paramName);
                params.put(paramName, paramValue);
            }
            
            logger.info("收到支付宝回调，订单号: {}, 交易状态: {}", 
                params.get("out_trade_no"), params.get("trade_status"));
            
            // 验证回调签名
            if (!paymentService.verifyAlipayCallback(params)) {
                logger.error("支付宝回调签名验证失败，订单号: {}", params.get("out_trade_no"));
                return "failure";
            }
            
            // 获取回调参数
            String tradeStatus = params.get("trade_status");      // 交易状态
            String outTradeNo = params.get("out_trade_no");       // 商户订单号
            String tradeNo = params.get("trade_no");              // 支付宝交易号
            String totalAmount = params.get("total_amount");      // 交易金额
            
            // 处理不同的交易状态
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                // 支付成功
                boolean success = donationService.handlePaymentSuccess(
                    outTradeNo,                    // 订单号
                    tradeNo,                       // 支付宝交易号
                    params.toString()              // 回调数据
                );
                
                if (success) {
                    logger.info("支付宝支付成功处理完成，订单号: {}, 交易号: {}", outTradeNo, tradeNo);
                    return "success";
                } else {
                    logger.error("支付宝支付成功处理失败，订单号: {}", outTradeNo);
                    return "failure";
                }
            } else if ("TRADE_CLOSED".equals(tradeStatus)) {
                // 交易关闭
                donationService.handlePaymentFailed(outTradeNo, "交易关闭：" + tradeStatus);
                logger.info("支付宝交易关闭，订单号: {}", outTradeNo);
                return "success";  // 对于关闭状态也返回success，表示已处理
            } else {
                // 其他状态（如等待付款等）
                logger.info("支付宝交易状态: {}, 订单号: {}", tradeStatus, outTradeNo);
                return "success";  // 返回success表示已接收到通知
            }
            
        } catch (Exception e) {
            logger.error("处理支付宝回调异常", e);
            return "failure";
        }
    }

    /**
     * 微信支付回调处理
     * 微信支付会通过POST方式发送XML格式的回调通知
     * @param request HTTP请求对象，包含微信支付回调数据
     * @return XML格式的处理结果
     */
    @PostMapping("/callback/wechat")
    public String handleWechatCallback(HttpServletRequest request) {
        try {
            // 读取微信回调数据
            StringBuilder xmlData = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                xmlData.append(line);
            }
            
            String xmlContent = xmlData.toString();
            logger.info("收到微信支付回调，数据长度: {}", xmlContent.length());
            
            // 验证回调签名
            if (!paymentService.verifyWechatCallbackXml(xmlContent)) {
                logger.error("微信支付回调签名验证失败");
                return buildWechatFailureResponse("签名验证失败");
            }
            
            // 解析XML数据（简化实现，实际项目中应使用专业的XML解析器）
            String resultCode = extractXmlValue(xmlContent, "result_code");
            String outTradeNo = extractXmlValue(xmlContent, "out_trade_no");
            String transactionId = extractXmlValue(xmlContent, "transaction_id");
            String totalFee = extractXmlValue(xmlContent, "total_fee");
            
            logger.info("微信支付回调解析，订单号: {}, 结果: {}, 交易号: {}", 
                outTradeNo, resultCode, transactionId);
            
            // 处理支付结果
            if ("SUCCESS".equals(resultCode)) {
                // 支付成功
                boolean success = donationService.handlePaymentSuccess(
                    outTradeNo,                    // 订单号
                    transactionId,                 // 微信交易号
                    xmlContent                     // 回调数据
                );
                
                if (success) {
                    logger.info("微信支付成功处理完成，订单号: {}, 交易号: {}", outTradeNo, transactionId);
                    return buildWechatSuccessResponse();
                } else {
                    logger.error("微信支付成功处理失败，订单号: {}", outTradeNo);
                    return buildWechatFailureResponse("处理失败");
                }
            } else {
                // 支付失败
                String errCodeDes = extractXmlValue(xmlContent, "err_code_des");
                donationService.handlePaymentFailed(outTradeNo, "支付失败：" + errCodeDes);
                logger.info("微信支付失败，订单号: {}, 原因: {}", outTradeNo, errCodeDes);
                return buildWechatSuccessResponse();  // 对于失败也返回success，表示已处理
            }
            
        } catch (Exception e) {
            logger.error("处理微信支付回调异常", e);
            return buildWechatFailureResponse("系统错误");
        }
    }

    /**
     * 云闪付回调处理
     * 云闪付会通过POST方式发送回调通知
     * @param request HTTP请求对象，包含云闪付回调参数
     * @return 处理结果
     */
    @PostMapping("/callback/unionpay")
    public Map<String, Object> handleUnionpayCallback(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取云闪付回调参数
            Map<String, String> params = new HashMap<>();
            Enumeration<String> parameterNames = request.getParameterNames();
            while (parameterNames.hasMoreElements()) {
                String paramName = parameterNames.nextElement();
                String paramValue = request.getParameter(paramName);
                params.put(paramName, paramValue);
            }

            logger.info("收到云闪付回调，订单号: {}, 交易状态: {}",
                params.get("orderId"), params.get("respCode"));

            // 验证回调签名
            if (!paymentService.verifyUnionpayCallback(params)) {
                logger.error("云闪付回调签名验证失败，订单号: {}", params.get("orderId"));
                result.put("success", false);
                result.put("message", "签名验证失败");
                return result;
            }

            // 获取回调参数
            String respCode = params.get("respCode");        // 应答码
            String orderId = params.get("orderId");          // 商户订单号
            String queryId = params.get("queryId");          // 流水号
            String txnAmt = params.get("txnAmt");            // 交易金额

            // 处理不同的应答码
            if ("00".equals(respCode)) {
                // 支付成功
                boolean success = donationService.handlePaymentSuccess(
                    orderId,                       // 订单号
                    queryId,                       // 云闪付流水号
                    params.toString()              // 回调数据
                );

                if (success) {
                    logger.info("云闪付支付成功处理完成，订单号: {}, 流水号: {}", orderId, queryId);
                    result.put("success", true);
                } else {
                    logger.error("云闪付支付成功处理失败，订单号: {}", orderId);
                    result.put("success", false);
                }
            } else {
                // 支付失败
                String respMsg = params.get("respMsg");
                donationService.handlePaymentFailed(orderId, "支付失败：" + respMsg);
                logger.info("云闪付支付失败，订单号: {}, 原因: {}", orderId, respMsg);
                result.put("success", true);  // 对于失败也返回success，表示已处理
            }

        } catch (Exception e) {
            logger.error("处理云闪付回调异常", e);
            result.put("success", false);
            result.put("message", "处理异常: " + e.getMessage());
        }

        return result;
    }

    /**
     * 查询支付状态
     * @param orderId 订单号
     * @return 支付状态信息
     */
    @GetMapping("/status/{orderId}")
    public Map<String, Object> getPaymentStatus(@PathVariable String orderId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取本地订单状态
            PaymentOrder order = paymentService.getPaymentOrder(orderId);
            if (order != null) {
                result.put("success", true);
                result.put("orderId", orderId);
                result.put("status", order.getStatus());
                result.put("paymentMethod", order.getPaymentMethod());
                result.put("amount", order.getAmount());
                result.put("createTime", order.getCreateTime());
                result.put("payTime", order.getPayTime());
                
                // 如果订单还在处理中，查询第三方支付状态
                if (PaymentOrder.STATUS_PAYING.equals(order.getStatus()) || 
                    PaymentOrder.STATUS_CREATED.equals(order.getStatus())) {
                    
                    Map<String, Object> thirdPartyStatus = paymentService.queryThirdPartyPaymentStatus(
                        orderId, order.getPaymentMethod());
                    result.put("thirdPartyStatus", thirdPartyStatus);
                }
            } else {
                result.put("success", false);
                result.put("message", "订单不存在");
            }
            
        } catch (Exception e) {
            logger.error("查询支付状态失败，订单号: " + orderId, e);
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 取消支付订单
     * @param orderId 订单号
     * @return 取消结果
     */
    @PostMapping("/cancel/{orderId}")
    @ResponseBody
    public Map<String, Object> cancelPayment(@PathVariable String orderId) {
        return paymentService.cancelPayment(orderId);
    }

    /**
     * 获取支付配置状态
     * @return 各支付方式的配置状态
     */
    @GetMapping("/config/status")
    public Map<String, Object> getPaymentConfigStatus() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Map<String, Boolean> configStatus = paymentService.checkAllPaymentConfigs();
            result.put("success", true);
            result.put("configStatus", configStatus);
            
            // 统计可用的支付方式数量
            long availableCount = configStatus.values().stream().mapToLong(b -> b ? 1 : 0).sum();
            result.put("availablePaymentMethods", availableCount);
            
        } catch (Exception e) {
            logger.error("获取支付配置状态失败", e);
            result.put("success", false);
            result.put("message", "获取配置状态失败");
        }
        
        return result;
    }

    // ==================== 辅助方法 ====================

    /**
     * 从XML中提取指定标签的值
     * @param xml XML字符串
     * @param tagName 标签名
     * @return 标签值
     */
    private String extractXmlValue(String xml, String tagName) {
        try {
            String startTag = "<" + tagName + "><![CDATA[";
            String endTag = "]]></" + tagName + ">";
            
            int startIndex = xml.indexOf(startTag);
            if (startIndex != -1) {
                startIndex += startTag.length();
                int endIndex = xml.indexOf(endTag, startIndex);
                if (endIndex != -1) {
                    return xml.substring(startIndex, endIndex);
                }
            }
            
            // 尝试普通标签格式
            startTag = "<" + tagName + ">";
            endTag = "</" + tagName + ">";
            startIndex = xml.indexOf(startTag);
            if (startIndex != -1) {
                startIndex += startTag.length();
                int endIndex = xml.indexOf(endTag, startIndex);
                if (endIndex != -1) {
                    return xml.substring(startIndex, endIndex);
                }
            }
            
            return "";
        } catch (Exception e) {
            logger.warn("解析XML标签失败: " + tagName, e);
            return "";
        }
    }

    /**
     * 构建微信支付成功响应
     * @return XML格式的成功响应
     */
    private String buildWechatSuccessResponse() {
        return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    }

    /**
     * 构建微信支付失败响应
     * @param message 失败消息
     * @return XML格式的失败响应
     */
    private String buildWechatFailureResponse(String message) {
        return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[" + message + "]]></return_msg></xml>";
    }

    /**
     * 手动触发支付成功处理（仅用于测试）
     * 将指定订单号的支付状态更新为成功
     */
    @PostMapping("/test/manual-success")
    @ResponseBody
    public Map<String, Object> manualPaymentSuccess(@RequestParam String orderId,
                                                   @RequestParam(required = false) String transactionId) {
        Map<String, Object> result = new HashMap<>();

        try {
            if (transactionId == null || transactionId.trim().isEmpty()) {
                transactionId = "TEST_" + System.currentTimeMillis();
            }

            boolean success = donationService.handlePaymentSuccess(orderId, transactionId, "手动测试触发");

            if (success) {
                result.put("success", true);
                result.put("message", "支付成功处理完成");
                result.put("orderId", orderId);
                result.put("transactionId", transactionId);
                logger.info("手动触发支付成功处理完成，订单号: {}, 交易号: {}", orderId, transactionId);
            } else {
                result.put("success", false);
                result.put("message", "支付成功处理失败，可能订单不存在或已处理");
            }

        } catch (Exception e) {
            logger.error("手动触发支付成功处理异常", e);
            result.put("success", false);
            result.put("message", "处理异常: " + e.getMessage());
        }

        return result;
    }

    /**
     * 支付请求DTO
     */
    public static class PaymentRequest {
        private String orderId;

        public String getOrderId() { 
            return orderId; 
        }
        
        public void setOrderId(String orderId) {
            this.orderId = orderId;
        }
    }

    /**
     * 测试支付成功处理（仅用于测试）
     * @param orderId 订单号
     * @return 处理结果
     */
    @RequestMapping(value = "/test/success/{orderId}", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> testPaymentSuccess(@PathVariable String orderId) {
        Map<String, Object> result = new HashMap<>();

        try {
            logger.info("开始测试支付成功处理，订单号: {}", orderId);

            // 先查询订单是否存在
            Map<String, Object> orderData = paymentService.getPaymentOrderData(orderId);
            logger.info("查询订单结果: {}", orderData);

            if (orderData == null) {
                result.put("success", false);
                result.put("message", "订单不存在: " + orderId);
                logger.error("订单查询返回null，订单号: {}", orderId);
                return result;
            }

            logger.info("找到订单: {}", orderData);

            // 模拟支付宝回调参数
            String tradeNo = "TEST_" + System.currentTimeMillis();
            String callbackData = "测试支付成功回调";

            logger.info("开始调用 handlePaymentSuccess，订单号: {}, 交易号: {}", orderId, tradeNo);

            boolean success = donationService.handlePaymentSuccess(orderId, tradeNo, callbackData);

            if (success) {
                // 再次查询订单状态验证更新结果
                Map<String, Object> updatedOrderData = paymentService.getPaymentOrderData(orderId);

                result.put("success", true);
                result.put("message", "测试支付成功处理完成");
                result.put("orderId", orderId);
                result.put("tradeNo", tradeNo);
                result.put("beforeUpdate", orderData);
                result.put("afterUpdate", updatedOrderData);

                logger.info("测试支付成功处理完成，订单号: {}", orderId);
            } else {
                result.put("success", false);
                result.put("message", "测试支付成功处理失败");
                logger.error("测试支付成功处理失败，订单号: {}", orderId);
            }

        } catch (Exception e) {
            logger.error("测试支付成功处理异常，订单号: " + orderId, e);
            result.put("success", false);
            result.put("message", "测试处理异常: " + e.getMessage());
            result.put("exception", e.getClass().getSimpleName());
        }

        return result;
    }

    /**
     * 测试支付取消处理（仅用于测试）
     * @param orderId 订单号
     * @return 处理结果
     */
    @PostMapping("/test/cancel/{orderId}")
    @ResponseBody
    public Map<String, Object> testPaymentCancel(@PathVariable String orderId) {
        Map<String, Object> result = new HashMap<>();

        try {
            boolean success = donationService.handlePaymentFailed(orderId, "用户取消支付");

            if (success) {
                result.put("success", true);
                result.put("message", "测试支付取消处理完成");
                result.put("orderId", orderId);
            } else {
                result.put("success", false);
                result.put("message", "测试支付取消处理失败");
            }

        } catch (Exception e) {
            logger.error("测试支付取消处理异常", e);
            result.put("success", false);
            result.put("message", "测试处理异常: " + e.getMessage());
        }

        return result;
    }

    /**
     * 调试订单查询（仅用于测试）
     * @param orderId 订单号
     * @return 查询结果
     */
    @GetMapping("/debug/order/{orderId}")
    @ResponseBody
    public Map<String, Object> debugOrderQuery(@PathVariable String orderId) {
        Map<String, Object> result = new HashMap<>();

        try {
            logger.info("开始调试订单查询，订单号: {}", orderId);

            // 1. 使用原生查询方法
            Map<String, Object> nativeData = paymentService.getPaymentOrderData(orderId);
            result.put("nativeQuery", nativeData);

            // 2. 使用 DTO 查询方法
            Object dtoData = paymentService.getPaymentOrderDto(orderId);
            result.put("dtoQuery", dtoData);

            // 3. 直接执行 SQL 查询（用于调试）
            result.put("orderId", orderId);
            result.put("success", true);

            logger.info("调试查询完成，订单号: {}, 原生查询结果: {}, DTO查询结果: {}",
                       orderId, nativeData != null, dtoData != null);

        } catch (Exception e) {
            logger.error("调试订单查询异常，订单号: " + orderId, e);
            result.put("success", false);
            result.put("message", "查询异常: " + e.getMessage());
            result.put("exception", e.getClass().getSimpleName());
        }

        return result;
    }
}
